package com.lzh.thinkpet.mail.impl;


import com.lzh.thinkpet.mail.SendJunkMailService;
import com.lzh.thinkpet.model.Admin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * @author lzh
 * @date 2019/1/15 - 15:34
 */
@Service
public class SendJunkMailServiceImpl implements SendJunkMailService {

    /**
     * 邮件发送接口
     */
    @Resource
    JavaMailSender mailSender;



    /**
     * @value 可以将配置文件中的属性加到变量中
     */
    @Value("${spring.mail.username}")
    private String from;

    public static final Logger logger = LogManager.getLogger(SendJunkMailServiceImpl.class);


    @Override
    public boolean sendJunkMail(List<Admin> adminList , String Subjuct , String SendTo , String MessageText) {

        try {
            if (adminList == null || adminList.size() <= 0){
                return Boolean.FALSE;

            }
            for (Admin ayUser : adminList){
                MimeMessage mimeMessage = this.mailSender.createMimeMessage();
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

                //邮件发送方
                message.setFrom(from);
                //邮件主题
                message.setSubject(Subjuct);
                //邮件接收方
                message.setTo(SendTo);
                //邮件内容
                message.setText(ayUser.getAdminName() +MessageText);
                //发送邮件
                this.mailSender.send(mimeMessage);

            }

        }catch (Exception ex){
            logger.error("sendJunkMail ERROR and ayUser=%s",adminList,ex);
            return Boolean.FALSE;

        }
        return Boolean.TRUE;

    }
}
